/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Ls_ctb_view",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using MyErp.IServices;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.CacheManager;
using VOL.Core.Extensions.AutofacManager;
using VOL.Core.Utilities;
using sysio = System.IO;
using sysnet = System.Net;
using VOL.Core.ManageUser;
using VOL.Core.Extensions;
using System.IO;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using OfficeOpenXml;
using System.Drawing;
using OfficeOpenXml.Style;
using System.Collections;

namespace MyErp.Controllers
{
    public partial class Ls_ctb_viewController
    {
        private readonly ILs_ctb_viewService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public Ls_ctb_viewController(
            ILs_ctb_viewService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 导出Excel,使用文件流下载文件
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("cbt_export"), AllowAnonymous]
        public ActionResult cbt_export()
        //public WebResponseContent cbt_export()
        {
            WebResponseContent content = new WebResponseContent();
            string path = null;
            string fileName = null;

            ICacheService cacheService = AutofacContainerModule.GetService<ICacheService>();
            string edate = cacheService.Get<string>(UserContext.Current.UserId.ToString() + "edate");//从内存中取出导出数据
            string bdate = cacheService.Get<string>(UserContext.Current.UserId.ToString() + "bdate");//从内存中取出导出数据
            bdate = "2022-05-10";
            edate = "2022-12-30";

            Console.WriteLine(bdate + "," + edate);
            if (bdate==null || edate == null)
            {
                return Content("请在高级查询中填写预测需求时间段开始/结束时间", "text/html");
            }

            List<Ls_ctb_view> dataList = cacheService.Get<List<Ls_ctb_view>>(UserContext.Current.UserId.ToString() + "list");
            fileName = "temp.xlsx";//随便给
            path = ExportGeneralExcel(dataList, fileName,bdate, edate);
            //content.Data = File(sysio.File.ReadAllBytes(path), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
            return File(sysio.File.ReadAllBytes(path), sysnet.Mime.MediaTypeNames.Application.Octet, fileName);
            //content.Message = "导出提示！";
            //return content;
        }
        public static string ExportGeneralExcel<T>(
                List<T> rows,
                string fileName,
                string bdate,
                string edate,
                string? path =null)
        {
            path = path ?? $"Download/ExcelExport/{DateTime.Now.ToString("yyyyyMMdd")}/";
            string fullPath = path.MapPath();
            fileName = Guid.NewGuid() + "_" + fileName;
            if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
            List<string> heads = new List<string>();
            heads.Add("物料编码");
            heads.Add("总成编码");
            heads.Add("type");
            heads.Add("stock");

            DateTime b_date = Convert.ToDateTime(bdate);
            DateTime e_date = Convert.ToDateTime(edate);
            DateTime b1 = DateTimeHelper_by_hxs.GetWeekFirstDayMon(b_date);//周第一天
            DateTime e9 = DateTimeHelper_by_hxs.GetWeekLastDaySun(e_date);//周最后天
            DateTime t = b1;
            while (t <= e9)
            {
                DateTime te = t.AddDays(6);
                int weekofyear = DateTimeHelper_by_hxs.GetWeekOfYear(t);//给定时间获取年度第几周 
                heads.Add("WK" + weekofyear + "(" + t.Month + "/" + t.Day + "-" + te.Month + "/" + te.Day + ")");
                t = t.AddDays(7);
            }

            using (ExcelPackage package = new ExcelPackage())
            {
                Color backgroundColor = Color.DarkOliveGreen;
                Color fontColor = Color.White;
                var worksheet = package.Workbook.Worksheets.Add("sheet1");
                int cn = 1;
                foreach (dynamic col in heads)//取出表头对应的中文
                {
                    worksheet.Cells[1, cn].Value = col.ToString();
                    worksheet.Cells[1, cn].Style.Fill.PatternType = ExcelFillStyle.Solid;//设置单元格颜色不能少
                    worksheet.Cells[1, cn].Style.Fill.BackgroundColor.SetColor(backgroundColor);//表头背景色
                    worksheet.Cells[1, cn].Style.Font.Color.SetColor(fontColor);
                    cn++;
                }
                //以上表头处理完毕，下面开始出来表格
                List<List<string>> table = new List<List<string>>();//table
                for (int i = 1; i <= 100; i++)
                {
                    List<string> row = new List<string>();//行
                    row.Add((i * 1).ToString());//给行添加0列
                    row.Add((i * 2).ToString());//给行添加1列
                    row.Add((i * 3).ToString());//给行添加2列
                    table.Add(row);
                }

                //int j = 0;
                for (int i = 0; i < table.Count; i++)
                {
                    List<string> row = table[i];//每行
                    for (int j = 0; j <= row.Count-1; j++)//每列
                    {  
                        worksheet.Cells[i + 2, j + 1].Value = row[j];          
                    }
                    worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();//自动填充单元格
                    for (var col = 1; col <= worksheet.Dimension.End.Column; col++)
                    {
                        worksheet.Column(col).Width = worksheet.Column(col).Width + 2;
                    }
                }
                package.SaveAs(new FileInfo(fullPath + fileName));
            }
            return path + fileName;
        }

        public static List<List<string>> tran_db_to_list_for_excel(List<Ls_ctb_view> dataList)
        {
            List<List<string>> list = new List<List<string>>();
            for (int i = 0; i < dataList.Count; i++)
            {
                //Demand行
                List<string> Demand = new List<string>();//行
                Demand.Add(dataList[i].mara);//给行添加0列
                Demand.Add(dataList[i].zc_mara);//给行添加1列
                Demand.Add("Demand");//给行添加2列
                list.Add(Demand);


                //Delivery行
                List<string> Delivery = new List<string>();//行
                Delivery.Add(dataList[i].mara);//给行添加0列
                Delivery.Add(dataList[i].zc_mara);//给行添加1列
                Delivery.Add("Delivery");//给行添加2列
                list.Add(Delivery);


                //Balance行
                List<string> Balance = new List<string>();//行
                Balance.Add(dataList[i].mara);//给行添加0列
                Balance.Add(dataList[i].zc_mara);//给行添加1列
                Balance.Add("Balance");//给行添加2列
                list.Add(Balance);

            }

            return list;
        }
    }
}
